package com.example.demo.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.demo.entity.BackResponseEntity;
import com.example.demo.entity.Post;
import com.example.demo.entity.PostFavorite;
import com.example.demo.entity.requestJson.DeleteReq;
import com.example.demo.entity.requestJson.FavoritePostReq;
import com.example.demo.entity.requestJson.QueryFavPostReq;
import com.example.demo.entity.responseJson.ListResult;
import com.example.demo.entity.responseJson.PostFavoriteRes;
import com.example.demo.enums.ErrCodeEnum;
import com.example.demo.mapper.LoginMapper;
import com.example.demo.mapper.PostFavoriteMapper;
import com.example.demo.mapper.PostMapper;
import com.example.demo.service.PostFavoriteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 帖子收藏表(PostFavorite)Service层
 *
 * @author 杨丽辉
 * @since 2021-03-15 10:43:24
 */
@Service
 @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
public class PostFavoriteServiceImpl implements PostFavoriteService {
        @Autowired
        private PostFavoriteMapper postFavoriteMapper;
        @Autowired
        private LoginMapper loginMapper;
        @Autowired
        private PostMapper postMapper;

 /**
     * 通过ID和其他条件查询单条数据
     *
     * @param postFavorite 实例对象
     * @return 实例对象
     */
       @Override
 @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
     public PostFavorite queryPostFavoriteLimit1(PostFavorite postFavorite){
     return  postFavoriteMapper.queryPostFavoriteLimit1( postFavorite);
     }
     
 /**
     * 查询指定行数据
     * @param postFavorite 实例对象
     * @param offset 查询起始位置
     * @param limit 查询条数
     * @return 对象列表
     */
       @Override
 @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
  public   List<PostFavorite> queryAllPostFavoriteByLimit( PostFavorite postFavorite, Integer offset,  Integer limit){
   return postFavoriteMapper.queryAllPostFavoriteByLimit(postFavorite, offset,limit);
  }

  /**
     * 查询数据条数
     * @return 条数
     */
       @Override
 @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
   public int countAllPostFavorite(PostFavorite postFavorite){
   return postFavoriteMapper.countAllPostFavorite( postFavorite);
   }
   /**
     * 通过实体作为筛选条件查询
     *
     * @param postFavorite 实例对象
     * @return 对象列表
     */
       @Override
 @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
   public List<PostFavorite> queryAllPostFavorite(PostFavorite postFavorite){
   return postFavoriteMapper.queryAllPostFavorite(postFavorite);
   }
  /**
     * 新增数据
     *
     * @param postFavorite 实例对象
     * @return 影响行数
     */
     @Override
   @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public int insertPostFavorite(PostFavorite postFavorite){
    return  postFavoriteMapper.insertPostFavorite( postFavorite);
    }
  /**
     * 修改数据
     *
     * @param postFavorite 实例对象
     * @return 影响行数
     */
       @Override
 @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
     public  int updatePostFavorite(PostFavorite postFavorite){
         return postFavoriteMapper.updatePostFavorite( postFavorite);
     }

    /**
     * 通过主键删除数据
     * @param postFavoriteId 主键
     * @return 影响行数
     */
      @Override
  @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
   public  int deletePostFavoriteById(String postFavoriteId){
   return  postFavoriteMapper.deletePostFavoriteById( postFavoriteId);
   }
     /**
     * 通过主键列表删除，列表长度不能为0
     * @param list 集合
     * @return 条数
     */
      @Override
  @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
  public  int deletePostFavoriteByIds( List<String> list){
    return  postFavoriteMapper.deletePostFavoriteByIds(  list);
  }
    
       /**
     * 通过主键修改实体列表，列表长度不能为0，注意：当实体属性为null时，对应的列也会别更新为null
     * @param list 集合
     * @return 条数
     */
       @Override
 @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
   public int updatePostFavoriteBatch( List<PostFavorite> list){
   return  postFavoriteMapper.updatePostFavoriteBatch(list);
   }
    /**
     * 批量其他列,除主键以外的列，列表长度不能为0,字段是空的就置为null
     * @param list 集合
     * @return 条数
     */
      @Override
  @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
 public   int insertPostFavoriteBatch( List<PostFavorite> list){
 return postFavoriteMapper.insertPostFavoriteBatch( list);
 }
      /**
     * 通过实体非空属性删除
     * @param postFavorite  实体
     * @return 条数
     */
        @Override
@Transactional(rollbackFor = {RuntimeException.class, Exception.class})
  public   int deletePostFavoriteByEntity( PostFavorite postFavorite){
  return  postFavoriteMapper.deletePostFavoriteByEntity(  postFavorite);
  }
    /**
     * 通过实体不为空的属性作为筛选条件查询列表
     * @param postFavorite  实体
     * @return list
     */
       @Override
 @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
   public  List<PostFavorite> listPostFavoriteByEntity(PostFavorite postFavorite){
   return postFavoriteMapper.listPostFavoriteByEntity( postFavorite);
   }

 /**
     * 新增实体属性不为null的列
     * @param postFavorite  实体
     * @return 条数
     */
       @Override
 @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
   public  int insertPostFavoriteSelect( PostFavorite postFavorite){
      return postFavoriteMapper.insertPostFavoriteSelect( postFavorite);

   }
   
      /**
     * 批量新增新增实体属性不为null的列
     * @param list  实体
     * @return 条数
     */
        @Override
@Transactional(rollbackFor = {RuntimeException.class, Exception.class})
  public  int insertPostFavoriteListSelect( List<PostFavorite> list){

     return postFavoriteMapper.insertPostFavoriteListSelect( list);
      }
     /**
     * 通过实体不为空的属性作为筛选条件查询单个
     * @param postFavorite  实体
     * @return 单个
     */
     @Override
   @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public  PostFavorite getPostFavoriteByEntity(PostFavorite postFavorite){
     return  postFavoriteMapper.getPostFavoriteByEntity(postFavorite);
    }

    /**
     * 收藏帖子
     * 1.调用接口查看是否收藏
     * 2.点击收藏
     * 3.图标变成已收藏，帖子放入书架，展示在个人中心的收藏作品中
     * */
    @Override
    public BackResponseEntity<Object> insertFavoritePost(FavoritePostReq favoritePostReq){

        if(ObjectUtils.isEmpty(favoritePostReq.getPostId()) || ObjectUtils.isEmpty(favoritePostReq.getUserId())){
            return BackResponseEntity.success(ErrCodeEnum.unknown_4006, "参数缺失");
        }

        LambdaQueryWrapper<Post> wrapper = new QueryWrapper<Post>().lambda();
        wrapper.select(Post::getPostName)
                .eq(Post::getPostId,favoritePostReq.getPostId());
        Post post = postMapper.selectOne(wrapper);

        PostFavorite postFavorite = new PostFavorite();
        postFavorite.setPostId(favoritePostReq.getPostId());
        postFavorite.setUserId(favoritePostReq.getUserId());
        postFavorite.setPostTitle(post.getPostName());
        postFavorite.setFavoriteTime(LocalDateTime.now());


        int i = postFavoriteMapper.insert(postFavorite);

        if(i > 0){

            Post post1 = new Post();
            int count = postMapper.countfavCount(Wrappers.<Post>query().eq("post_id", favoritePostReq.getPostId())) +1;
            post1.setPostId(favoritePostReq.getPostId());
            post1.setFavoriteCount(count);

            int m = postMapper.updatePost(post1);

            return BackResponseEntity.success(ErrCodeEnum.unknown_0, "收藏成功");
        }else {
            return BackResponseEntity.success(ErrCodeEnum.unknown_1013, "收藏失败");
        }
    }

    /**
     * 查询书架所有帖子,也用于查看个人主页收藏作品
     * 传入userid
     * */
    @Override
    public BackResponseEntity<ListResult<List<PostFavoriteRes>>> querybookshelefPost(DeleteReq deleteReq){
        String id = null;

        if(!ObjectUtils.isEmpty(deleteReq.getId())){
            id = deleteReq.getId()
                    .trim();
        }
        if(ObjectUtils.isEmpty(id)){
            return BackResponseEntity.success(ErrCodeEnum.unknown_4006, "参数缺失");
        }

        List<PostFavoriteRes> list = postFavoriteMapper.querybookshelefPost(Wrappers.<PostFavorite>query().eq("user_id", id));

        int count = postFavoriteMapper.countbookshelefPost(Wrappers.<PostFavorite>query().eq("user_id", id));
        ListResult<List<PostFavoriteRes>> listResult = new ListResult((int)count, list);

        return BackResponseEntity.success(ErrCodeEnum.unknown_0, listResult, "");

    }

    /**
     * 是否收藏该书
     * */
    @Override
    public BackResponseEntity<Object> isfavoritePost(FavoritePostReq favoritePostReq){

        if(ObjectUtils.isEmpty(favoritePostReq.getUserId()) || ObjectUtils.isEmpty(favoritePostReq.getPostId())){
            return BackResponseEntity.success(ErrCodeEnum.unknown_4006, "参数缺失");
        }
        if(postFavoriteMapper.isFavoritePost(Wrappers.<PostFavorite>query().eq("user_id", favoritePostReq.getUserId())
                .eq("post_id", favoritePostReq.getPostId())) == 0){
            return BackResponseEntity.success(ErrCodeEnum.unknown_1047, "未收藏书籍");
        }else {
            return BackResponseEntity.success(ErrCodeEnum.unknown_1048, "已收藏该书籍");
        }
    }

    /**
     * 取消收藏
     * 1.进行取消操作
     * 2.相应的收藏数减少
     * 3.删除关注表中的记录
     * */
    @Override
    public BackResponseEntity<Object> unSubscribePost(FavoritePostReq favoritePostReq){
        String userId = null;
        String postId = null;

        if(!ObjectUtils.isEmpty(favoritePostReq.getPostId())){
            postId = favoritePostReq.getPostId()
                    .trim();
        }
        if(!ObjectUtils.isEmpty(favoritePostReq.getUserId())){
            userId = favoritePostReq.getUserId()
                    .trim();
        }
        if(ObjectUtils.isEmpty(userId) || ObjectUtils.isEmpty(postId)){
            return BackResponseEntity.success(ErrCodeEnum.unknown_4006, "参数缺失");
        }
        PostFavorite postFavorite = new PostFavorite();
        postFavorite.setUserId(userId);
        postFavorite.setPostId(postId);
        int i = postFavoriteMapper.deletePostFavoriteByEntity(postFavorite);

        if( i > 0 ){
            Post post = new Post();
            int count = postMapper.countfavCount(Wrappers.<Post>query().eq("post_id", postId))-1;

            post.setPostId(postId);
            post.setFavoriteCount(count);
            int m = postMapper.updatePost(post);

            return BackResponseEntity.success(ErrCodeEnum.unknown_0, "取消收藏注成功");
        }else {
            return BackResponseEntity.success(ErrCodeEnum.unknown_1017, "取消收藏失败");
        }

    }


    /**
     * 模糊查询收藏书籍（用户书架搜索）
     * */
    @Override
    public BackResponseEntity<List<PostFavoriteRes>> fuzzyQueryPost(QueryFavPostReq queryFavPostReq){
        String userId = null;
        String postName = null;

        if(!ObjectUtils.isEmpty(queryFavPostReq.getUserId())){
            userId = queryFavPostReq.getUserId()
                    .trim();
        }
        if(!ObjectUtils.isEmpty(queryFavPostReq.getPostName())){
            postName = queryFavPostReq.getPostName()
                    .trim();
        }
        if(ObjectUtils.isEmpty(userId) || ObjectUtils.isEmpty(postName)){
            return BackResponseEntity.success(ErrCodeEnum.unknown_4006, "搜索条件不能为空");
        }

        List<PostFavoriteRes> list = postFavoriteMapper.querybookshelefPost(Wrappers.<PostFavorite>query().eq("user_id", userId)
                .like("post_title", postName));

        return BackResponseEntity.success(ErrCodeEnum.unknown_0, list, "");

    }

}

